package cn.tedu.tea.ex;

import cn.tedu.tea.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.net.BindException;
import java.util.Set;
import java.util.StringJoiner;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public String handleNullPointerException(NullPointerException e) {
        return "程序出现了空指针异常，已经被处理！";
    }

    @ExceptionHandler
    public String handleRuntimeException(RuntimeException e) {
        log.debug("RuntimeException={}",e);
        return "程序出现了RuntimeException，已经被处理！";
    }

    @ExceptionHandler
    public R handleBindException(BindException e){
        log.info("请求参数格式错误");
        String message = e.getLocalizedMessage();
        log.info("message={}",message);
//        String defaultMessage = e.getFieldError().getDefaultMessage();
        return R.fail(null,400,message);
    }

    @ExceptionHandler
    public R handleBindException(MethodArgumentNotValidException e){
        log.info("请求参数格式错误={}");
        String defaultMessage = e.getFieldError().getDefaultMessage();
        return R.fail(null,400,defaultMessage);
    }

    @ExceptionHandler
    public R handleConstraintViolationException(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        String delimiter = "，";
        StringJoiner stringJoiner = new StringJoiner(delimiter);
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            stringJoiner.add(constraintViolation.getMessage());
        }
        return R.fail(null,400, stringJoiner.toString());
    }

    @ExceptionHandler
    public R handleServiceException(ServiceException e) {
        String message = e.getMessage();
        return R.fail(null,e.getServiceCode().getCode(), message);
    }
}